package com.ajie.slimming.ui.fragment;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ajie.slimming.R;
import com.ajie.slimming.ui.BaseFragment;
import com.ajie.slimming.ui.MainActivity;
import com.ajie.slimming.ui.SlimmingApplication;
import com.ajie.slimming.ui.view.ProgressWheel;
import com.ajie.slimming.util.DataManager;
import com.ajie.slimming.util.Util;
import com.ajie.slimming.widget.CustomPopupWindow;
import com.example.bluetooth.le.BluetoothLeService;
import com.example.bluetooth.le.DeviceScanActivity;

/**
 * 成绩
 * 
 * @author mhealth
 * 
 */
public class ResultFragment extends BaseFragment implements OnClickListener {
	private String TAG = ResultFragment.class.getSimpleName();

	private final int REQUEST_CODE = 0;

	/****************************************************************/
	private BluetoothLeService mBluetoothLeService;

	private BluetoothGattCharacteristic mNotifyCharacteristic;

	private boolean mConnected = false;

	private String mDeviceName;

	private String mDeviceAddress;

	private String currentData = "";

	public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";

	public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

	// Code to manage Service lifecycle.
	private final ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName,
				IBinder service) {
			mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
					.getService();
			if (!mBluetoothLeService.initialize()) {
				Log.e(TAG, "Unable to initialize Bluetooth");
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			mBluetoothLeService = null;
		}
	};

	// 接收service发来的广播
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				mConnected = true;
				updateUI(R.string.connected);
			} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
					.equals(action)) {
				mConnected = false;
				updateUI(R.string.disconnected);
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
					.equals(action)) {
				// Show all the supported services and characteristics on the
				// user interface.
				Log.d(TAG, "gatt_services_discovered");
				handleGattServices(mBluetoothLeService
						.getSupportedGattServices());
			} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				Log.d(TAG, "action_data_available");
				String data = intent
						.getStringExtra(BluetoothLeService.EXTRA_DATA);
				currentData += data;
				if (currentData.endsWith("ff")) {
					Log.d(TAG, "save success data :" + currentData);
					String result = currentData.substring(
							currentData.indexOf("fd"),
							currentData.indexOf("ff") + 2);
					currentData = "";
					if (dataManager.saveData(result)) {
						Log.d(TAG, "result data :" + result);
						updateUI(R.string.synchronize_success);
						refreshData();
					} else {
						updateUI(R.string.synchronize_failed);
					}
				}
			}
		}
	};

	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter
				.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
		return intentFilter;
	}

	private void handleCharacteristic(BluetoothGattCharacteristic characteristic) {
		final int charaProp = characteristic.getProperties();
		if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
			// If there is an active notification on a characteristic, clear
			// it first so it doesn't update the data field on the user
			// interface.
			if (mNotifyCharacteristic != null) {
				mBluetoothLeService.setCharacteristicNotification(
						mNotifyCharacteristic, false);
				mNotifyCharacteristic = null;
			}
			mBluetoothLeService.readCharacteristic(characteristic);
		}
		if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
			mNotifyCharacteristic = characteristic;
			mBluetoothLeService.setCharacteristicNotification(characteristic,
					true);
		}
	}

	private void handleGattServices(List<BluetoothGattService> gattServices) {
		if (gattServices == null)
			return;
		for (BluetoothGattService gattService : gattServices) {
			List<BluetoothGattCharacteristic> gattCharacteristics = gattService
					.getCharacteristics();
			for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
				handleCharacteristic(gattCharacteristic);
			}
		}
	}

	// 更新界面上显示的蓝牙状态
	private void updateUI(final int resourceId) {
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				showToast(resourceId);
			}
		});
	}

	/****************************************************************/
	// 同步按钮
	private TextView synchronize = null;

	private Button shareBtn = null;

	// 页面数据
	private TextView this_calorie, this_weight, history_calorie,
			history_weight;

	private TextView layout_when_no_data;

	private RelativeLayout layout_when_exist_data;

	private TextView percent, time;

	private DataManager dataManager;

	
	private ProgressWheel progressWheel_01;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent gattServiceIntent = new Intent(getActivity(),
				BluetoothLeService.class);
		getActivity().bindService(gattServiceIntent, mServiceConnection,
				Activity.BIND_AUTO_CREATE);

		dataManager = new DataManager();

		try {
			InputStream in = getResources().getAssets().open("share_img.png");
			OutputStream out = new FileOutputStream(
					SlimmingApplication.getImageRootDir() + "/share.png");
			byte buff[] = new byte[1024];
			while ((in.read(buff)) != -1) {
				out.write(buff);
			}
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		getActivity().registerReceiver(mGattUpdateReceiver,
				makeGattUpdateIntentFilter());
		if (mBluetoothLeService != null) {
			final boolean result = mBluetoothLeService.connect(mDeviceAddress);
			Log.d(TAG, "Connect request result=" + result);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		getActivity().unregisterReceiver(mGattUpdateReceiver);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unbindService(mServiceConnection);
		mBluetoothLeService = null;
	}

	View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_main, container, false);
		setTitle(R.string.result);
		setOption(0);
		initViews(view);
		dataManager.saveData("");
		if (dataManager.hasData()) {
			refreshData();
		}
		// if (helper.isInfoComplete())
		// {
		// layout_when_no_data.setVisibility(View.GONE);
		// layout_when_exist_data.setVisibility(View.VISIBLE);
		// }
		return view;
	}

	private void initViews(View view) {
		synchronize = (TextView) view.findViewById(R.id.synchronize);
		this_calorie = (TextView) view.findViewById(R.id.this_calorie);
		this_weight = (TextView) view.findViewById(R.id.this_weight);
		history_calorie = (TextView) view.findViewById(R.id.history_calorie);
		history_weight = (TextView) view.findViewById(R.id.history_weight);

		layout_when_no_data = (TextView) view
				.findViewById(R.id.layout_when_no_data);
		layout_when_exist_data = (RelativeLayout) view
				.findViewById(R.id.layout_when_exist_data);
		percent = (TextView) view.findViewById(R.id.percent);
		time = (TextView) view.findViewById(R.id.use_time);

		shareBtn = (Button) view.findViewById(R.id.share);
		shareBtn.setOnClickListener(this);
		synchronize.setOnClickListener(this);

		customPopupWindow = new CustomPopupWindow(getActivity(),
				customPopupWindowClickListener);
		
		progressWheel_01 = (ProgressWheel) view.findViewById(R.id.progressWheel_01);
//		progressWheel_01.incrementProgress(25);
		animationPlay(progressWheel_01, 56);
	}
	
	
	private void animationPlay(final ProgressWheel progressWheel,final int num) {
	    Runnable progressWheel_run = new Runnable() {
			public void run() {
				int progress = 0;
				while(progress<361) {
					progressWheel.incrementProgress(num);
					progress++;
					try {
						Thread.sleep(8);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
	    };
	    Thread progressWheel_thread = new Thread(progressWheel_run);
		progressWheel_thread.start();
	}
	    

	private void refreshData() {
		Log.d(TAG, "refreshing Data");
		String thisCal = dataManager.getLatestCalorie();
		String totalCal = dataManager.getTotalCalorie();
		this_calorie.setText(thisCal + "卡");
		this_weight.setText("约"
				+ String.format("%.2f", Util.getHeatWeight(thisCal)) + "kg脂肪");
		history_calorie.setText(totalCal + "卡");
		history_weight.setText("约"
				+ String.format("%.2f", Util.getHeatWeight(totalCal)) + "kg脂肪");
		// percent.setText(helper);
		// time.setText(helper);
	}

	private CustomPopupWindow customPopupWindow;

	private OnClickListener customPopupWindowClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.share_qq:
				System.out.println("share_qq");
				 ((MainActivity)getActivity()).shareImageToQZone("15");
				break;
			case R.id.share_weixin:
				System.out.println("share_weixin");
				((MainActivity)getActivity()).shareImageToFriend("15");
				break;
			case R.id.share_pengyouquan:
				System.out.println("share_pengyouquan");
				((MainActivity)getActivity()).shareImageToCircle("15");
				break;
			case R.id.share_xinlang:
				System.out.println("share_xinlang");
				Toast.makeText(getActivity(), "申请新浪还未批准", Toast.LENGTH_LONG).show();
				break;
			case R.id.button_cancel:
				System.out.println("button_cancel");
				break;
			default:
				break;
			}
			customPopupWindow.dismiss();
		}
	};

	@Override
	public void onClick(View v) {
		Intent serverIntent = null;
		switch (v.getId()) {
		case R.id.synchronize:
			// ensure bt is enable
			serverIntent = new Intent(getActivity(), DeviceScanActivity.class);
			// serverIntent = new
			// Intent(getActivity(),DeviceListActivity.class);
			startActivityForResult(serverIntent, REQUEST_CODE);
			break;

		case R.id.share:
			// ((MainActivity)getActivity()).shareImageToQZone("15");
			customPopupWindow.showAtLocation(view.findViewById(R.id.result_fragment), Gravity.BOTTOM, 0,0);
			// File file = new File(SlimmingApplication.getImageRootDir()
			// + "/share.png");
			// String calorie = dataManager.getLatestCalorie();
			// Intent intent = new Intent(Intent.ACTION_SEND);
			// intent.setType("image/*");
			// intent.putExtra(Intent.EXTRA_SUBJECT, "来自imeiga塑身仪的分享");
			// if (TextUtils.isEmpty(calorie)
			// || TextUtils.equals(calorie, "0"))
			// {
			// intent.putExtra(Intent.EXTRA_TEXT,
			// "新一代塑身神器到手啦！躺着就能消耗脂肪，期待身材越来越苗条哦~ 淘宝搜索：imeiga塑身仪，加入我的团队，大家一起来PK吧~ ^_^");
			// }
			// else
			// {
			// intent.putExtra(Intent.EXTRA_TEXT, "盆友们，不用运动，躺着就消耗了"
			// + calorie
			// + "卡路里，身材越来越苗条~淘宝搜索：imeiga塑身仪，加入我的团队，大家一起来PK吧~ ^_^");
			// }
			// intent.putExtra(Intent.EXTRA_TITLE, "imeiga塑身仪");
			// intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
			// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			// startActivity(intent);
			break;
		default:
			break;
		}
	}

	// private void shareToTimeLine()
	// {
	// Intent intent = new Intent();
	// ComponentName comp = new ComponentName("com.tencent.mm",
	// "com.tencent.mm.ui.tools.ShareToTimeLineUI");
	// intent.setComponent(comp);
	// intent.setAction("android.intent.action.SEND");
	// intent.setType("image/*");
	// intent.putExtra(Intent.EXTRA_TEXT, "我是文字");
	// startActivity(intent);
	// }

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
			mDeviceName = data.getStringExtra(EXTRAS_DEVICE_NAME);
			mDeviceAddress = data.getStringExtra(EXTRAS_DEVICE_ADDRESS);
			// Automatically connects to the device upon successful start-up
			// initialization.
			mBluetoothLeService.connect(mDeviceAddress);
		}
	}
}
